package com.ruoyi.genpdf.service;

import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.*;
import com.itextpdf.layout.properties.*;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class LotteryPdfService {

    private Map<String, PdfFont> fontCache = new HashMap<>();

    public Resource generateLotteryTicket() throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        PageSize pageSize = new PageSize(mmToPoints(80), mmToPoints(101));

        // 创建PDF文档
        PdfWriter writer = new PdfWriter(outputStream);
        PdfDocument pdf = new PdfDocument(writer);
        Document document = new Document(pdf, pageSize); // 使用小尺寸页面

        float topBottomMargin = mmToPoints(10);    // 上下边距
        float leftRightMargin = mmToPoints(5); // 左右边距
        document.setMargins(topBottomMargin, leftRightMargin, topBottomMargin, leftRightMargin);

        // 设置中文字体（需要确保系统有中文字体）
        PdfFont font = PdfFontFactory.createFont();
        document.setFont(font);

        //String fontPath = "D:\\idea\\ruoyi_project\\ruoyi-caip\\ruoyi-caip\\ruoyi-system\\src\\main\\resources\\fonts\\hb1.otf";

        String hb1Path = "";
        String stPath = "";
        File filehb = new PathMatchingResourcePatternResolver().getResource("fonts/hb1.otf").getFile();
        File filest = new PathMatchingResourcePatternResolver().getResource("fonts/宋体与数字结合.ttf").getFile();

        if (filehb.isFile()) {
            hb1Path = filehb.getAbsolutePath();
            stPath = filest.getAbsolutePath();
        } else {
            return null;
        }

        String hjzhu = " 2";
        String bs =  "5";
        String zhum = "20";
        String money = "50";
        String code = "85B3-4643-0683-9C06-CEB5/13666289/C0056";
        String kjq = "2025270 25-10-11";
        String xsq = "2025270-223";
        String xssj = "25-10-11 19:47:04";
        String address = "地址：山东省枣庄市市中区好运有你福彩专营店";
        String gongyi = "感谢您为公益事业贡献6.80元";

        PdfFont customFont = PdfFontFactory.createFont(hb1Path, PdfEncodings.IDENTITY_H);

        PdfFont customFontst = PdfFontFactory.createFont(stPath, PdfEncodings.IDENTITY_H);

        PdfFont bdfh = PdfFontFactory.createFont(hb1Path, PdfEncodings.IDENTITY_H);

        Text textbd = new Text(": ");
        textbd.setFontSize(12f);
        textbd.setFont(bdfh);
        textbd.setBold();

        // 添加标题
        Paragraph title = new Paragraph("玩法:3D-复式                机号:37040015")
                .setFont(customFont)
                .setFontSize(9.5F)
                .setTextAlignment(TextAlignment.LEFT);
        document.add(title);

        // 添加代码信息
        Paragraph pcode = new Paragraph(code)
                .setMarginTop(-7)
                .setFont(customFont)
                .setFontSize(9.5F)
                .setTextAlignment(TextAlignment.LEFT);
        document.add(pcode);


        Div div = new Div();
        // 设置固定高度
        div.setHeight(UnitValue.createPointValue(mmToPoints(30)));
        div.setTextAlignment(TextAlignment.CENTER);
        div.setProperty(Property.JUSTIFY_CONTENT, JustifyContent.CENTER); // 垂直居中

        // 设置边框和背景以便可视化
        //div.setBorder(new SolidBorder(1f));
        //div.setBackgroundColor(ColorConstants.LIGHT_GRAY);

        Text rightTextElement = new Text(hjzhu);
        rightTextElement.setFontSize(12f);
        rightTextElement.setBold();

        Text rightTextElement2 = new Text("注");
        rightTextElement2.setFontSize(10.5f);

        // 添加组三复式投注信息
        Paragraph betType = new Paragraph("组三复式投注")
                .setMarginTop(10)
                //.setMarginLeft(18)
                .setFont(customFont)
                .setFontSize(10.5f)
                //.setBold()
                .setTextAlignment(TextAlignment.CENTER)
                .add(textbd)
                .add("\t")
                .add("合计")
                .addTabStops(new TabStop(250f, TabAlignment.RIGHT))
                .add("\t")
                .add(rightTextElement)
                //.addTabStops(new TabStop(1f, TabAlignment.RIGHT))
                .add("\t")
                .add(rightTextElement2);
        div.add(betType);

        Text textzm = new Text(zhum);
        textzm.setFontSize(12f);
        textzm.setFont(customFontst);
        textzm.setBold();
        // 添加注释和倍数
        Paragraph comment = new Paragraph("注码")
                .setMarginTop(-5)
                .setFont(customFont)
                .setFontSize(10.5f)
                //.setBold()
                .setTextAlignment(TextAlignment.LEFT)
                .setMarginLeft(73)
                //.add("\t")
                .add(textbd)
                .add(textzm);
        div.add(comment);

        Text textbs = new Text(bs);
        textbs.setFontSize(12f);
        textbs.setFont(customFontst);
        textbs.setBold();
        Paragraph multiple = new Paragraph("倍数")
                .setMarginTop(-5)
                .setFont(customFont)
                .setFontSize(10.5f)
                //.setBold()
                .setTextAlignment(TextAlignment.LEFT)
                .setMarginLeft(73)
                //.add("\t")
                .add(textbd)
                .add(textbs);
        div.add(multiple);
        document.add(div);


        Text texthj = new Text(money);
        texthj.setFontSize(12f);
        texthj.setFont(customFontst);
        texthj.setBold();

        Text textbd2 = new Text(":");
        textbd2.setFontSize(12f);
        textbd2.setFont(bdfh);
        textbd2.setBold();

        Paragraph kaijiang = new Paragraph("开奖期："+kjq+"    合计")
                .setMarginTop(-5)
                .setFont(customFont)
                .setFontSize(9)
                .setTextAlignment(TextAlignment.LEFT)
                //.add("\t")
                .add(textbd2)
                .add(texthj)
                //.add("\t")
                .add("元");
        document.add(kaijiang);


        Paragraph xiaoshou = new Paragraph("销售期："+xsq+"     "+xssj)
                .setMarginTop(-5)
                .setFont(customFont)
                .setFontSize(9)
                .setTextAlignment(TextAlignment.LEFT);
        document.add(xiaoshou);

        // 添加地址信息
        Paragraph paddress = new Paragraph(address)
                .setMarginTop(-5)
                .setFont(customFont)
                .setFontSize(9)
                .setTextAlignment(TextAlignment.LEFT);
        document.add(paddress);

        // 添加公益信息
        Paragraph donation = new Paragraph(gongyi)
                .setMarginTop(-5)
                .setFont(customFont)
                .setFontSize(9)
                .setTextAlignment(TextAlignment.LEFT);
        document.add(donation);

        //String impath = "D:\\idea\\ruoyi_project\\ruoyi-caip\\ruoyi-caip\\ruoyi-system\\src\\main\\resources\\static\\1.png";

        File fileimage = new PathMatchingResourcePatternResolver().getResource("static/1.png").getFile();

        Paragraph pimage = new Paragraph();
        ImageData imageData = ImageDataFactory.create(fileimage.getAbsolutePath());
        Image image = new Image(imageData);

        // 设置图片大小
        image.setWidth(mmToPoints(91));  // 91mm宽度
        image.setHeight(mmToPoints(22.5f)); // 22.5mm高度
        image.setMarginTop(-5);
        image.setMarginLeft(-3);
        image.setBold();
        image.setAutoScale(true);

        // 添加图片到段落
        pimage.add(image);
        document.add(pimage);

        document.close();

        return new ByteArrayResource(outputStream.toByteArray());
    }

    private Cell createCell(String text, int fontSize, boolean bold) {
        Paragraph paragraph = new Paragraph(text)
                .setFontSize(fontSize);
        if (bold) {
            paragraph.setBold();
        }
        return new Cell().add(paragraph).setPadding(2);
    }

    /**
     * 毫米转点
     */
    private float mmToPoints(float mm) {
        return mm * 2.83465f;
    }

    /**
     * 像素转换为点
     */
    private float pixelsToPoints(float pixels) {
        return pixels * 0.75f;
    }
}
